<?php
/**
 * Created by PhpStorm.
 * User: Sixstar-Peter
 * Date: 2019/3/21
 * Time: 22:03
 */

use Swoole\WebSocket\Server;

class Route
{

    public function run()
    {

        $this->server = new Server('0.0.0.0', 9600);
        $this->server->set([
            'worker_num' => 2
        ]);

//        $this->server->on('Start',[$this,'start']);
        $this->server->on('workerStart', [$this, 'workerStart']);
        $this->server->on('handShake', [$this, 'handShake']);
        $this->server->on('open', [$this, 'open']);
        $this->server->on('message', [$this, 'message']);
        $this->server->on('close', [$this, 'close']);
        $this->server->on('request', [$this, 'request']);

        $this->server->start();

    }

    public function open()
    {

    }

    public function handShake(\swoole_http_request $request, \swoole_http_response $response)
    {
        // print_r( $request->header );
        //通过判断websocket请求头当中是否有一个有效token
        if (!isset($request->header['sec-websocket-protocol'])) {
            $response->end();
            return false;
            //todo jwt校验
        }

        // websocket握手连接算法验证
        $secWebSocketKey = $request->header['sec-websocket-key'];
        $patten = '#^[+/0-9A-Za-z]{21}[AQgw]==$#';
        if (0 === preg_match($patten, $secWebSocketKey) || 16 !== strlen(base64_decode($secWebSocketKey))) {
            $response->end();
            return false;
        }
        echo $request->header['sec-websocket-key'];
        $key = base64_encode(sha1(
            $request->header['sec-websocket-key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
            true
        ));

        $headers = [
            'Upgrade' => 'websocket',
            'Connection' => 'Upgrade',
            'Sec-WebSocket-Accept' => $key,
            'Sec-WebSocket-Version' => '13',
        ];

        // WebSocket connection to 'ws://127.0.0.1:9502/'
        // failed: Error during WebSocket handshake:
        // Response must not include 'Sec-WebSocket-Protocol' header if not present in request: websocket
        if (isset($request->header['sec-websocket-protocol'])) {
            $headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol'];
        }

        foreach ($headers as $key => $val) {
            $response->header($key, $val);
        }

        $response->status(101);
        $response->end();
    }

    public function workerStart($server, $workerId)
    {
        $this->redis = new Redis();
//        $this->redis->setOption();
        $this->redis->pconnect('127.0.0.1', 6379);
    }

    public function request($server, $request)
    {
        $data = $request->post;
        switch ($data['method']) {
            case 'login':
                //1.权限验证颁发token

                //2.通过算法返回服务器地址跟token
                break;
        }

    }

    public function message($server, $frame)
    {
        $data = json_decode($frame->data, true);
        switch ($data['method']) {
            case 'register':
                $service_key = 'service' . $data['serviceName'];
                echo $service_key;
                $value = [
                    'ip' => $data['ip'],
                    'port' => $data['port']
                ];
                $this->redis->sadd($service_key, json_encode($value));
                $redis = $this->redis;
                $fd = $frame->fd;
                //会存在诺记的情况，主动清楚
                swoole_timer_tick(3000, function ($timer_id) use ($redis, $fd, $server, $service_key) {
                    //检测fd是否存活
                    if (!$server->exist($fd)) {
                        //删除redis中的服务
                        $redis->del($service_key);

                        //中止定时器
                        swoole_timer_clear($timer_id);
                    }

                });
                break;

            case 'delete':

                break;
        }
        var_dump($frame);
    }

    public function close($server, $fd)
    {


    }


}

